import { View, Text } from '@tarojs/components'
import PageContainer from '@/components/PageContainer'
import i18n from "i18n-js"
import { useCallback, useMemo, useRef, useState } from 'react';
import { GStyleSheet } from '@/utils/DarkMode';
import { ActionSheet, Button, DatetimePicker } from '@taroify/core';
import ListItem from '@/components/ListItem';
import Taro, { useDidShow } from '@tarojs/taro';
import { GButton } from '@/components/GButton'
import { ISchedulerConfig } from '@/config/product'
import Toast from '@/utils/Toast'
import { useDeviceRect } from '@/hooks/useDeviceRect'
import { getDetail } from '../utils/detailModel'
import { getTimeText, getRepeatText, scheduleToServiceSchedule } from '../utils/tool'
import { addSchedule, editSchedule, IAddParamSchedule, IEditParamSchedule } from '../utils/scheduleApi'
import { getSchedulerConfig } from '../utils/scheduleConfig'
import SchedulerOptItem from './SchedulerOptItem';



const SetTimingScreen = () => {
  const [detail, setDetail] = useState(getDetail()!)
  console.log('Detail', detail)
  const [timeOpen, setTimeOpen] = useState(false)
  const [date, setDate] = useState(detail.dateObj.toDate())
  const styles = dstyles.useDynamicStyle();
  const { safeAreaBottomHeight } = useDeviceRect()

  const savingRef = useRef(false);
  const save = useCallback(async () => {
    if (savingRef.current) {
      return;
    }
    // 先检查是不是有设置attrs
    if (!detail.attrs) {
      Toast.info('未设置定时要执行的功能')
      return;
    }
    savingRef.current = true;
    const d = scheduleToServiceSchedule(detail)
    Toast.showLoading({ content: '' });
    if (detail.id) {
      const res = await editSchedule(d as IEditParamSchedule).finally(() => {
        savingRef.current = false;
      });
      console.log(res);
      Toast.hideLoading()
      if (res.success) {
        Toast.success('编辑成功')
        Taro.navigateBack()
      } else {
        Toast.error('编辑失败')
      }
    } else {
      const res = await addSchedule(d as IAddParamSchedule).finally(() => {
        savingRef.current = false;
      });
      console.log(res);
      Toast.hideLoading()
      if (res.success) {
        Toast.success('添加成功')
        Taro.navigateBack()
      } else {
        Toast.error('添加失败')
      }
    }
  }, [detail])

  useDidShow(() => {
    console.log('useDidShow')
    setDetail(d => ({ ...d, repeatArray: getDetail()!.repeatArray }))
  })

  const handleConfirmDate = useCallback(() => {
    setDetail(d => ({ ...d, timeObj: { hour: date.getHours(), minute: date.getMinutes() } }))
    setTimeOpen(false)
  }, [date])

  const handleCancelDate = useCallback(() => {
    setTimeOpen(false)
  }, [])

  const goToRepeat = useCallback(() => {
    Taro.navigateTo({ url: '/pages/scheduler/setRepeat/index' })
  }, [])

  const schedulerConfigList = useMemo(() => {
    return getSchedulerConfig()
  }, [])

  const onChange = useCallback(({ schedule, value }: { schedule: ISchedulerConfig, value: any }) => {
    const newAttrs = { [schedule.attr]: value }
    setDetail(d => ({ ...d, attrs: { ...d.attrs, ...newAttrs } }))
  }, [])

  return (
    <PageContainer title='定时设置'>
      <View style={styles.container}>
        <View style={{ paddingTop: 15 }}>
          {schedulerConfigList.map((config) => {
            return <SchedulerOptItem key={config.name} schedule={config} onChange={onChange} value={(detail?.attrs ?? {})[config.attr ?? '']} />
          })}
          <ListItem
            arrow
            onPress={() => {
              setTimeOpen(true)
              const d = detail.dateObj.toDate()
              d.setHours(detail.timeObj.hour)
              d.setMinutes(detail.timeObj.minute)
              setDate(d)
            }}
            extra={<Text style={styles.text}>{getTimeText(detail.timeObj)}</Text>}
          >
            执行时间
          </ListItem>
          <ListItem
            arrow
            extra={<Text style={styles.text}>{getRepeatText({ schedule: detail, isFocus: true })}</Text>}
            onPress={goToRepeat}
          >
            重复
          </ListItem>
        </View>
        <GButton text={i18n.t('SAVE')} onPress={save} />
      </View>

      <ActionSheet
        open={timeOpen}
        onClose={setTimeOpen}
        onCancel={() => setTimeOpen(false)}
        style={{ paddingBottom: safeAreaBottomHeight }}
      >
        <ActionSheet.Header>执行时间</ActionSheet.Header>
        <DatetimePicker
          type='hour-minute'
          style={{ position: 'relative' }}
          value={date}
          onChange={(d) => {
            setDate(d)
          }}
        >
          <Text style={styles.hour}>时</Text>
          <Text style={styles.minute}>分</Text>
        </DatetimePicker>
        <View style={{ display: 'flex' }}>
          <Button variant='text' style={{ flex: 1 }} onClick={handleCancelDate}>取消</Button>
          <View style={{ width: 1, height: 45, backgroundColor: '#F1F1F1' }} />
          <Button variant='text' style={{ flex: 1 }} onClick={handleConfirmDate}>确定</Button>
        </View>
      </ActionSheet>
    </PageContainer>
  )
}

const dstyles = GStyleSheet.create({
  container: {
    display: 'flex',
    width: '100%',
    height: '100%',
    flexDirection: 'column',
    justifyContent: 'space-between',
  },
  text: { fontSize: 15, color: '#333', fontWeight: 400 },
  hour: {
    position: 'absolute',
    top: '50%',
    transform: 'translateY(-50%)',
    left: '31%'
  },
  minute: {
    position: 'absolute',
    top: '50%',
    transform: 'translateY(-50%)',
    right: '15%'
  },
});

export default SetTimingScreen
